//
//  CustomNaviBarSearchController.m
//  CustomDemo
//
//  Created by 于洪东 on 16/6/24.
//  Copyright © 2016年 于洪东. All rights reserved.
//

#define WS(weakSelf)  __weak __typeof(&*self)weakSelf = self;

#import "CustomNaviBarSearchController.h"
#import "GlobalDefine.h"
#import <Masonry.h>


@interface CustomNaviBarSearchController ()<UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) CustomViewController *viewCtrlParent;
@property (nonatomic,strong) UIView *viewNaviBar;
@property (nonatomic,strong) UISearchBar *searchBar;
@property (nonatomic,strong) UIButton *btnCancel;

@property (nonatomic,strong) UIButton *backButton;
@property (nonatomic,strong) UIButton *searchButton;
@property (nonatomic,strong) UILabel *middleLabel;

@property (nonatomic,strong) NSArray *arrRecent;
@property (nonatomic,strong) UITableView *tableView;


@end


@implementation CustomNaviBarSearchController

-(instancetype)init{
    if (self = [super init]) {
        
    }
    return self;
}

-(id)initWithParentViewCtrl:(CustomViewController *)viewCtrl{
    if (self = [super init]) {
        APP_ASSERT(viewCtrl);
        _viewCtrlParent = viewCtrl;
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(theScreenRotation) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
    }
    return self;
}

#pragma mark - 响应方法
-(void)cancelButtonClick:(UIButton *)sender{
    NSLog(@"取消按钮点击");
    
    [self endSearch];
    
    // 代理方法回调
    if ([self.delegate respondsToSelector:@selector(naviBarSearchCtrlCancel:)]) {
        [self.delegate naviBarSearchCtrlCancel:self];
    }
}

-(void)theScreenRotation{
    
//    __weak __typeof(&*_viewCtrlParent)weakSelf = _viewCtrlParent;

    if ([UIScreen mainScreen].bounds.size.width>[UIScreen mainScreen].bounds.size.height) {
        // heng ping
        NSLog(@"heng ping");
        
        [_tableView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(@32);
        }];

    }else{
        // shu ping
        NSLog(@"shu ping");
        [_tableView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(@64);
        }];
    }
}

/**
 *  返回按钮点击
 */
-(void)backButtonClick:(UIButton *)sender{
    [_viewCtrlParent.navigationController popViewControllerAnimated:YES];
}

/**
 *  搜索按钮点击
 */
-(void)searchButtonClick:(UIButton *)sender{
    
    [self startSearch];
    
    [_searchBar becomeFirstResponder];

    _searchBar.hidden = NO;
    _btnCancel.hidden = NO;
    _backButton.hidden = YES;
    _middleLabel.hidden = YES;
    _searchButton.hidden = YES;
    
}

/**
 *  取消按钮点击
 */
-(void)cancelTempButtonClick:(UIButton *)sender{
    
    [self endSearch];
    
    _searchBar.hidden = YES;
    _btnCancel.hidden = YES;
    _backButton.hidden = NO;
    _middleLabel.hidden = NO;
    _searchButton.hidden = NO;
}


/**
 *  清空搜索记录
 */
- (void)btnClearSearchRecord:(id)sender{
    if ([self.delegate respondsToSelector:@selector(naviBarSearchCtrlClearKeywordRecord:)]){
        [self.delegate naviBarSearchCtrlClearKeywordRecord:self];
    }else{}
}

#pragma mark - public method

- (void)resetPlaceHolder:(NSString *)strMsg{
    _searchBar.placeholder = strMsg;
}

- (void)setRecentKeyword:(NSArray *)arrRecentKeyword{
    if (arrRecentKeyword){
        _arrRecent = [NSArray arrayWithArray:arrRecentKeyword];
    }
    else{
        _arrRecent = nil;
    }
    if (_tableView){
        [_tableView reloadData];
    }else{}
}

-(void)setKeyword:(NSString *)strKeyword{

}

/**
 *  导航条上一直显示输入框
 */
-(void)showFixationSearchCtrl{
    [self initFixationUI];
}

/**
 *  由按钮触发，点击按钮后显示输入框，结束后销毁输入框现实按钮。
 */

-(void)showTempSearchCtrl{
    [self initTempUI];
}

-(void)removeSearchCtrl{

}


#pragma mark - UISearchBarDelegate

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    NSLog(@"键盘上的搜索按钮点击");
    
    if (searchBar.text) {
        NSString *strKeyword = [[searchBar.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] copy];
        
        if (strKeyword.length>0) {
            [self endSearch];
            if ([self.delegate respondsToSelector:@selector(naviBarSearchCtrl:searchKeyword:)]) {
                [self.delegate naviBarSearchCtrl:self searchKeyword:strKeyword];
            }
        }else{
            searchBar.text = @"";
        }
    }else{}
    
    
    
 
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    NSLog(@"点击搜索框后 searchBarTextDidBeginEditing");
    [self startSearch];
}

#pragma mark - 私有方法
/**
 *  设置searchBar的背景色为透明
 */
-(void)p_setSearchBarBackground:(UISearchBar *)searchBar{
    
    for (UIView *subview in searchBar.subviews) {
        for(UIView* grandSonView in subview.subviews){
            if ([grandSonView isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
                grandSonView.alpha = 0.0f;
                [grandSonView removeFromSuperview];
            }else if([grandSonView isKindOfClass:NSClassFromString(@"UISearchBarTextField")] ){
                NSLog(@"Keep textfiedld bkg color");
            }else{
                grandSonView.alpha = 0.0f;
                [grandSonView removeFromSuperview];
            }
        }
    }
}

-(void)startSearch{
    // 显示出取消按钮
    [_btnCancel mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(@50);
    }];
    // 展示tableView
    [self showRecentTable:YES];
}

- (void)endSearch{
    
    if (_searchBar.tag == 10086) {
        _searchBar.text = @"";
        [_searchBar resignFirstResponder];
        // 隐藏取消按钮
        [_btnCancel mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(@0);
        }];
        // 隐藏tableView
        [self showRecentTable:NO];
    }else if (_searchBar.tag == 10010){
        _searchBar.text = @"";
        [_searchBar resignFirstResponder];
        // 隐藏取消按钮
        [_btnCancel mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(@0);
        }];
        // 隐藏tableView
        [self showRecentTable:NO];
        
        
        _searchBar.hidden = YES;
        _btnCancel.hidden = YES;
        _backButton.hidden = NO;
        _middleLabel.hidden = NO;
        _searchButton.hidden = NO;
        
        
    }else{}
    
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSInteger iCount = _arrRecent ? _arrRecent.count : 0;
    return iCount;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"SearchTypeCell";
    
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    
    cell.backgroundColor = [UIColor clearColor];
    cell.textLabel.textColor = RGB_TextDarkGray;
    cell.textLabel.font = [UIFont systemFontOfSize:SIZE_TextLarge];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    NSString *strKeyword = _arrRecent[indexPath.row];
    cell.textLabel.text = strKeyword;
    
    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *strKeyword = _arrRecent[indexPath.row];
    [_searchBar setText:strKeyword];
}

#pragma mark - set和get方法

/**
 *  设置控件
 */
-(void)initFixationUI{
    
    APP_ASSERT(_viewCtrlParent);
    
    _viewNaviBar = [[UIView alloc]init];
    _viewNaviBar.backgroundColor = [UIColor redColor];
    _viewNaviBar.userInteractionEnabled = YES;
    [_viewCtrlParent.viewBar showCoverView:_viewNaviBar];
    
    
    _searchBar = [[UISearchBar alloc]init];
    _searchBar.userInteractionEnabled = YES;
    _searchBar.placeholder = @"请输入搜索条件";
    _searchBar.backgroundColor = [UIColor cyanColor];
    _searchBar.delegate = self;
    _searchBar.tag = 10086;
    [_viewNaviBar addSubview:_searchBar];
    [self p_setSearchBarBackground:_searchBar];
    
    
    _btnCancel = [UIButton buttonWithType:UIButtonTypeCustom];
    [_btnCancel setTitle:@"取消" forState:UIControlStateNormal];
    [_btnCancel setBackgroundColor:[UIColor blackColor]];
    [_btnCancel setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_btnCancel addTarget:self action:@selector(cancelButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [_viewNaviBar addSubview:_btnCancel];
    
    [self layoutFixationSubViewConstrains];
    
}

-(void)initTempUI{
    
    APP_ASSERT(_viewCtrlParent);
    
    _viewNaviBar = [[UIView alloc]init];
    _viewNaviBar.backgroundColor = [UIColor redColor];
    _viewNaviBar.userInteractionEnabled = YES;
    [_viewCtrlParent.viewBar showCoverView:_viewNaviBar];
    
    
    _searchBar = [[UISearchBar alloc]init];
    _searchBar.userInteractionEnabled = YES;
    _searchBar.placeholder = @"请输入搜索条件";
    _searchBar.backgroundColor = [UIColor cyanColor];
    _searchBar.delegate = self;
    _searchBar.tag = 10010;
    [_viewNaviBar addSubview:_searchBar];
    [self p_setSearchBarBackground:_searchBar];
    
    
    _btnCancel = [UIButton buttonWithType:UIButtonTypeCustom];
    [_btnCancel setTitle:@"取消" forState:UIControlStateNormal];
    [_btnCancel setBackgroundColor:[UIColor blackColor]];
    [_btnCancel setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_btnCancel addTarget:self action:@selector(cancelTempButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [_viewNaviBar addSubview:_btnCancel];
    
    
    
    _middleLabel = [[UILabel alloc]init];
    _middleLabel.text = @"这是试验";
    _middleLabel.font = [UIFont systemFontOfSize:18];
    _middleLabel.textColor = [UIColor blackColor];
    _middleLabel.textAlignment = NSTextAlignmentCenter;
    [_viewNaviBar addSubview:_middleLabel];
    
    
    _backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_backButton setTitle:@"返回" forState:UIControlStateNormal];
//    _backButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [_backButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [_backButton addTarget:self action:@selector(backButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [_viewNaviBar addSubview:_backButton];

    
    _searchButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_searchButton setImage:[UIImage imageNamed:@"NaviBtn_Search"] forState:UIControlStateNormal];
    [_searchButton setImage:[UIImage imageNamed:@"NaviBtn_Search_H"] forState:UIControlStateHighlighted];
    [_searchButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [_searchButton addTarget:self action:@selector(searchButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [_viewNaviBar addSubview:_searchButton];
    
    

    
    [self layoutTempSubViewConstrains];
    
}


- (void)showRecentTable:(BOOL)bIsShow{
    if (bIsShow && _arrRecent && (_arrRecent.count > 0)){
        if (!_tableView){
            _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStylePlain];
            [_viewCtrlParent.view addSubview:_tableView];
            _tableView.backgroundColor = RGBA(235.0f, 235.0f, 235.0f, 1.0f);
            _tableView.delegate = self;
            _tableView.dataSource = self;
            
            UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0,0,0,44)];
            footerView.backgroundColor = [UIColor clearColor];
            _tableView.tableFooterView = footerView;
            
            NSLog(@"%@",footerView);
            
            UIButton *clearButton = [UIButton buttonWithType:UIButtonTypeCustom];
            clearButton.frame = CGRectMake(0, 0,[UIScreen mainScreen].bounds.size.width,footerView.frame.size.height);
            [clearButton setTitle:@"清除搜索记录" forState:UIControlStateNormal];
            [clearButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [clearButton setTitleColor:[UIColor purpleColor] forState:UIControlStateHighlighted];
            [clearButton addTarget:self action:@selector(btnClearSearchRecord:) forControlEvents:UIControlEventTouchUpInside];
            [footerView addSubview:clearButton];
            
            
            __weak __typeof(&*_viewCtrlParent)weakSelf = _viewCtrlParent;

            [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(weakSelf.view);
                make.right.equalTo(weakSelf.view);
                make.bottom.equalTo(weakSelf.view);
                make.top.mas_equalTo(@64);
            }];

        }else{}
    }else{
        if (_tableView){
            [_tableView removeFromSuperview];
            _tableView = nil;
        }else{}
    }
}
/**
 *  对控件的约束  -----   好像有问题  原因是布局所依赖的视图的frame是0;
 */
-(void)layoutFixationSubViewConstrains{
    WS(weakSelf);
    
    NSLog(@"%@",_viewNaviBar);
    
    [_btnCancel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(weakSelf.viewNaviBar).offset(0);
        make.height.mas_equalTo(@30);
        make.right.equalTo(weakSelf.viewNaviBar).offset(0);
        make.width.mas_equalTo(@0);
    }];
    
    [_searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.viewNaviBar).offset(0);
        make.bottom.equalTo(weakSelf.viewNaviBar).offset(0);
        make.right.equalTo(weakSelf.btnCancel.mas_left);
        make.left.equalTo(weakSelf.viewNaviBar);
    }];
}

-(void)layoutTempSubViewConstrains{
    WS(weakSelf);
    
    NSLog(@"%@",_viewNaviBar);

    [_backButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(weakSelf.viewNaviBar).offset(0);
        make.left.equalTo(weakSelf.viewNaviBar);
        make.width.mas_equalTo(@50);
        make.height.mas_equalTo(@30);
    }];
    
    [_searchButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(weakSelf.viewNaviBar).offset(0);
        make.height.mas_equalTo(@30);
        make.right.equalTo(weakSelf.viewNaviBar).offset(0);
        make.width.mas_equalTo(@30);
    }];
    
    [_middleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.viewNaviBar);
        make.right.equalTo(weakSelf.viewNaviBar);
        make.centerY.equalTo(weakSelf.viewNaviBar);
        make.height.mas_equalTo(@30);
    }];
    
    
    [_btnCancel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(weakSelf.viewNaviBar).offset(0);
        make.height.mas_equalTo(@30);
        make.right.equalTo(weakSelf.viewNaviBar).offset(0);
        make.width.mas_equalTo(@0);
    }];
    
    [_searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.viewNaviBar).offset(0);
        make.bottom.equalTo(weakSelf.viewNaviBar).offset(0);
        make.right.equalTo(weakSelf.btnCancel.mas_left);
        make.left.equalTo(weakSelf.viewNaviBar);
    }];
    
    
    _btnCancel.hidden = YES;
    _searchBar.hidden = YES;
    
}




@end
